<?php

use luguohuakai\func\Func;
use luguohuakai\ini\Ini;

require '/usr/lib/zabbix/alertscripts/vendor/autoload.php';

$send_to = $argv[1]; // open_id
$subject = dealThing($argv[2]); // 项目名称 20个以内字符 可汉字、数字、字母或符号组合
$message = $argv[3]; // 告警原因
$app_id = $argv[4];
$app_secret = $argv[5];
$template_id = $argv[6];

$arr = explode('|', $message);

$message = dealThing($arr[0]);
$status = dealThing($arr[2]); // {TRIGGER.STATUS}事件状态 5个以内汉字
$hostname = dealThing($arr[3]); // {HOST.IP}告警对象

function dealThing($str)
{
    if (mb_strlen($str) == 0) return '--';
    if (mb_strlen($str) <= 20) return $str;
    return mb_substr($str, 0, 17) . '...';
}

switch (strtolower($status)) {
    case 'ok':
        $status = '已恢复';
        break;
    case 'problem':
        $status = '进行中';
        break;
    default:
        $status = '进行中';
}

$access_token = '';
$ini = Ini::load('/usr/lib/zabbix/alertscripts/wechat_template.ini');
$expires_time = $ini->get('wechat_template_expires_time');
if ($expires_time && $expires_time > time()) $access_token = $ini->get('wechat_template_access_token');
if (!$access_token) {
    $url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$app_id&secret=$app_secret";
    $rs = Func::get($url1);
    if ($rs) {
        $res = json_decode($rs);
        if ($res) {
            if (isset($res->access_token)) {
                $access_token = $res->access_token;
                $ini->setAll(['wechat_template_expires_time' => $res->expires_in + time(), 'wechat_template_access_token' => $access_token]);
            } else {
                L("request error: no access_token");
            }
        } else {
            L('json_decode error: ' . print_r($rs, true));
        }
    } else {
        L('request wechat server error: ' . $url1);
    }
}

if ($access_token) {
    $url2 = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$access_token";

    $data = [
        'touser' => $send_to,
        'template_id' => $template_id,
        'data' => [
            'thing95' => ['value' => $subject], // 项目名称
            'thing2' => ['value' => $hostname], // 告警对象
            'thing70' => ['value' => $message], // 告警原因
            'phrase9' => ['value' => $status], // 事件状态
            'time3' => ['value' => date('Y-m-d H:i:s')], // 告警时间
        ]
    ];

    $result = Func::post($url2, $data, [], 2);

    if ($result) {
        $res2 = json_decode($result);
        if ($res2 && $res2->errcode == 0) {
            L('发送成功: ' . $subject . json_encode($data, JSON_UNESCAPED_UNICODE), 'info');
        } else {
            L("发送失败: $res2->errcode : $res2->errmsg" . json_encode($data, JSON_UNESCAPED_UNICODE));
        }
    } else {
        L('request error: ' . $url2);
    }
} else {
    L('access_token not exists.');
}

function L($data, $level = 'error')
{
    Func::logs('zbx', $data, 'human-readable', FILE_APPEND, 'month', $level);
}